package se.boars.dailystatistics;

import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.IBinder;
import android.preference.PreferenceManager;

public class bgUpdate extends Service{
	
	SharedPreferences settings;
	SharedPreferences.Editor editor;
	NotificationManager nManager;
	JSONParser jParser = new JSONParser();
	int questionId;
	boolean alive = true;
	
	@Override
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		super.onStart(intent, startId);
		ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
		param.add(new BasicNameValuePair("tag", "getQuestionId"));
		boolean alive = true;
		if(isNetworkAvailable() == true) {
			JSONObject jObj = jParser.getJSONObjectFromWeb("http://108.174.49.135/rewrite/api.php", param);
			try {
				questionId = jObj.getInt("id");
				editor.putInt("questionId", questionId);
				System.out.println("onStart questionId: " + questionId);
			} catch (JSONException e) {
				System.out.println("Error in service at onStart: " + e);
			}
		}
	}

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		System.out.println("Killing service");
		alive = false;
	}
	
	@Override
	public void onCreate() {
		super.onCreate();
		settings = PreferenceManager.getDefaultSharedPreferences(this);
		editor = settings.edit();
		Thread updateThread = new Thread() {
			@Override
			public void run() {
				try {
					while(alive == true) {
						sleep(5000);
						if(isNetworkAvailable() == true) {
							ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
							param.add(new BasicNameValuePair("tag", "getQuestionId"));
							JSONObject jObj = jParser.getJSONObjectFromWeb("http://108.174.49.135/rewrite/api.php", param);
							questionId = jObj.getInt("id");	
							System.out.println("onCreate questionId: " + questionId);
							compareId(questionId);
						} else {
							System.out.println("No network connection available");
							run();
						}
					}
				} catch (Exception e) {
					System.out.println("Error in service at updateThread: " + e);
					run();
				}
			}
	};
	updateThread.start();
}
	
	public void compareId(int id) {
		int prevId = settings.getInt("questionId", 0);
		System.out.println("compare sharedsettings previd: " + prevId);
		if(prevId < id) {
			System.out.println("New question available");
			editor.putInt("questionId", id);
			editor.commit();
			Intent intent = new Intent(this,tabHost.class);  

			nManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
			
			Notification notification = new Notification(R.drawable.ic_launcher, "Daily Statistics: New question available!", System.currentTimeMillis());
			notification.flags |= Notification.FLAG_AUTO_CANCEL;
			notification.setLatestEventInfo(bgUpdate.this, "Daily Statistics", "New question available", PendingIntent.getActivity(this.getBaseContext(), 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
			long[] vibrate = {0,100,200,300};
		    notification.vibrate = vibrate;
		    notification.defaults |= Notification.DEFAULT_SOUND;
		    notification.ledARGB = 0xff00ff00;
		    notification.ledOnMS = 300;
		    notification.ledOffMS = 1000;
		    notification.flags |= Notification.FLAG_SHOW_LIGHTS;
			nManager.notify(0, notification);
		} else {
			System.out.println("No new question available");
		}
	}
	
	public boolean isNetworkAvailable() {
	    ConnectivityManager cm = (ConnectivityManager) 
	    	getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo networkInfo = cm.getActiveNetworkInfo();
	    // if no network is available networkInfo will be null
	    // otherwise check if we are connected
	    if (networkInfo != null && networkInfo.isConnected()) {
	        return true;
	    }
	    return false;
	}
}
